package com.atguigu.gulimall.search.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 异步编排-任务组合，两个完成才可
 *
 * @author LaiSanShan
 * @date 2021-08-18
 */
public class CompletableFuture3Test {

    private static ExecutorService threadPool = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main启动。。。");
        // 1.
//        CompletableFuture.supplyAsync(() -> {
//            System.out.println("任务1执行。。。返回1");
//            return 1;
//        }, threadPool)
//                .runAfterBoth(CompletableFuture.supplyAsync(() -> {
//                    System.out.println("任务2执行。。。返回2");
//                    return 2;
//                }), new ThreadTask());
        // 2.
//        CompletableFuture.supplyAsync(() -> {
//            System.out.println("任务1执行。。。返回1");
//            return 1;
//        }, threadPool)
//                .thenAcceptBothAsync(CompletableFuture.supplyAsync(() -> {
//                    System.out.println("任务2执行。。。返回2");
//                    return 2;
//                }), (res1, res2) -> {
//                    System.out.println("任务3执行，拿到res1：" + res1 + "；拿到res2：" + res2);
//                }, threadPool);
        // 3.
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务1执行。。。返回1");
            return 1;
        }, threadPool)
                .thenCombineAsync(CompletableFuture.supplyAsync(() -> {
                    System.out.println("任务2执行。。。返回2");
                    return 2;
                }), (res1, res2) -> {
                    System.out.println("任务3执行，拿到res1：" + res1 + "；拿到res2：" + res2 + "；并返回其和");
                    return res1 + res2;
                }, threadPool);
        Integer res = completableFuture.get();
        System.out.println("最终结果：" + res);
        System.out.println("main结束。。。");
    }

    public static class ThreadTask implements Runnable {
        @Override
        public void run() {
            System.out.println("后续任务执行。。。");
        }
    }

}
